Passed
Push — development ( 2f9cbb...cdc56b )
by Peter
09:24 queued 15s
created

AdminGate.tsx ➔ AdminGate   B

Complexity

Conditions 5

Size

Total Lines 38
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5.0729

Importance

Changes 0
Metric Value
cc 5
eloc 31
dl 0
loc 38
ccs 18
cts 21
cp 0.8571
crap 5.0729
rs 8.6693
c 0
b 0
f 0
1
import { useEffect, useState } from 'react'
2
3
import { useSelector } from 'react-redux';
4
import { RootState } from '../redux/store/store';
5
import axios, { AxiosError } from 'axios';
6
import { API_URL, getHeader } from '../helpers/config';
7
import { useNavigate } from "react-router-dom";
8
import {  toast } from 'react-toastify';
9
10
11
export default function AdminGate() {
12 29
    const {isLoggedIn, token, user } = useSelector((state: RootState) =>  state.auth);
13 21
    const navigate = useNavigate();
14
15 21
    const [myAuthorizations, setMyAuthorizations] = useState<string[]>([])
16
17 21
    const getMyAuthorizations = async () => {
18 8
        if (isLoggedIn) {
19 2
                try {
20 2
                    const response = await axios.get(`${API_URL}/auth/me`, getHeader(token));
21 2
                    setMyAuthorizations(response.data.roles);
22
                } catch (error) {
23
                    const axiosError = error as AxiosError;
24
                    toast.error(axiosError.message);
25
                    setMyAuthorizations(['NotLoggedIn']);
26
                }
27
            }  else {
28 6
                setMyAuthorizations(['NotLoggedIn']);
29
            }
30
        }
31
   
32 21
    useEffect(() => {
33 8
        getMyAuthorizations();
34
    }, [user, isLoggedIn, token])
35
36 21
    useEffect(() => {
37 16
        if (myAuthorizations.length < 1) 
38 8
            return;
39
40 8
        if ( !myAuthorizations.includes("admin")) {
41 7
            toast.error("This page requires admin access, sending you back to homepage");
42 7
            navigate("/");
43
        } 
44
   
45
    }, [myAuthorizations]);
46 21
  return null;
47
}
48